import axios from 'axios'
import { ElMessage, ElLoading } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { getMAC } from '@/utils/getMAC';
const instance = axios.create({
    baseURL: import.meta.env.VITE_APP_API,
    withCredentials: false,
})

// 请求拦截器
instance.interceptors.request.use(
    async config => {
        const macAddress = await getMAC();
        config = {
            neddLogin: true,
            ...config,
        }

        const userStore = useUserStore()

        if (config.neddLogin) {
            if (userStore.checkLogin()) {
                // config.headers['Ql-Token'] = userStore.user?.token
                // config.headers['Ql-Uid'] = userStore.user?.uid
                // config.headers['Ql-Gid'] = userStore.user?.gid

                config.headers['Authorization'] = `TOKEN ` + userStore.userdata.combins.auto_bet_fz.accessToken
            }
        }
        config.headers['PLANTCODE'] = 'auto_bet_fz'
        config.headers['MAC'] = macAddress

        return config
    },
    error => {
        ElMessage.error('请求超时')
        Promise.reject(error)
    }
)

// 相应拦截器
instance.interceptors.response.use(
    response => {
        const { data, status } = response

        if (status && status == 200) {
            // if ([403].includes(data.code)) {
            //   ElMessage.warning(data.msg || '账号已过期，请重新登录')
            //   const userStore = useUserStore()
            //   userStore.logout()
            //   return Promise.reject(data)
            // } 
            if ([401].includes(data.code)) {
                ElMessage.warning(data.data.msg || '账号已过期，请重新登录')
                const userStore = useUserStore()
                userStore.logout()
                // return Promise.reject(data)
            } else if (data.code != 200) {
                ElMessage.error(data.msg)
                return Promise.reject(data)
            }

            return data
        } else {

            ElMessage.error('接口错误')
            return Promise.reject(data)
        }
    },
    error => {
        if (error?.response?.status == 401 || error?.response?.status == 400) {
            ElMessage.warning(error?.response?.data?.msg || '账号已过期，请重新登录')
            const userStore = useUserStore()
            userStore.logout()
            return
        } else if (error?.response?.status == undefined) {
            // ElMessage.error('请求超时')
            const userStore = useUserStore()
            userStore.openerrordialog()
        } else {
            ElMessage.error('请求超时')
            // const userStore = useUserStore()
            // userStore.openerrordialog()
        }


        return Promise.reject(error)
    }
)

export const http = instance
export default instance
